package com.sfx.messagequeue.mqServer.datacenter;

import com.sfx.messagequeue.common.exception.MQException;
import com.sfx.messagequeue.mqServer.core.Binding;
import com.sfx.messagequeue.mqServer.core.Exchange;
import com.sfx.messagequeue.mqServer.core.MSGQueue;
import com.sfx.messagequeue.mqServer.core.Message;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description: 统一硬盘操作
 * User: sfx
 * Date: 2023-08-03
 * Time: 20:09
 */
public class DiskDataCenter {
    //数据库操作
    private DataBaseManager dataBaseManager = new DataBaseManager();
    //文件操作
    private MessageFileManager messageFileManager = new MessageFileManager();

    public void init() {
        dataBaseManager.init();
        messageFileManager.init();
    }

    //1.插入交换机
    public void insertExchange(Exchange exchange) throws IOException {
        dataBaseManager.insertExchange(exchange);
    }

    //2.删除交换机
    public void deleteExchange(String exchangeName) {
        dataBaseManager.deleteExchange(exchangeName);
    }

    //3.查询所有交换机
    public List<Exchange> selectAllExchange() {
        return dataBaseManager.selectAllExchange();
    }

    //1.增加队列
    public void insertQueue(MSGQueue queue) throws IOException {
        dataBaseManager.insertQueue(queue);
        // 创建队列的同时, 不仅仅是把队列对象写到数据库中, 还需要创建出对应的目录和文件
        messageFileManager.createQueueFiles(queue.getName());
    }

    //2.删除队列
    public void deleteQueue(String queueName) {
        dataBaseManager.deleteQueue(queueName);
        // 创建队列的同时, 不仅仅是把队列对象写到数据库中, 还需要创建出对应的目录和文件
        messageFileManager.deleteFiles(queueName);
    }

    //3.查询所有队列
    public List<MSGQueue> selectAllQueue() {
        return dataBaseManager.selectAllQueue();
    }

    //1.增加绑定
    public void insertBinding(Binding binding) {
        dataBaseManager.insertBinding(binding);
    }

    //2.删除绑定
    public void deleteBinding(Binding binding) {
        dataBaseManager.deleteBinding(binding);
    }

    //3.查询所有绑定
    public List<Binding> selectAllBindings() {
        return dataBaseManager.selectAllBinding();
    }

    //1.保存消息到文件
    public void sendMessage(MSGQueue queue, Message message) throws MQException, IOException {
        messageFileManager.sendMessage(queue,message);
    }

    //2.删除消息
    public void deleteMessage(MSGQueue queue,Message message) throws MQException, IOException, ClassNotFoundException {
        messageFileManager.deleteMessage(queue,message);
        if(messageFileManager.checkGC(queue.getName())) {
            messageFileManager.gc(queue);
        }
    }

    //3.加载消息
    public LinkedList<Message> loadAllMessageFromQueue(String queueName) throws MQException, IOException, ClassNotFoundException {
        return messageFileManager.loadAllMessageFromQueue(queueName);
    }
}